package com.cakebackoffice;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.cakebackoffice.Model.*;

import java.util.HashMap;
import java.util.Iterator;


public class CatalogMenuActivity extends Activity {

    private Dialog dialog;


    private Long idActualCategory;
    private Long idSelectedProduct = null;
    private Long selectedMenu = null;

    static final int CREATE_CATEGORY = 0;
    static final int CREATE_PRODUCT = 1;
    static final int CREATE_MENU = 2;
    static final int CREATE_EDIT_PROPERTY = 3;

    private CatalogPropertyEnum selectedProperty;

    public void setIdActualCategory(Long idActualCategory) {
        this.idActualCategory = idActualCategory;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.catalog_menu_fragment);

    }

    protected Dialog onCreateDialog(int id) {

        switch (id) {
            case CREATE_CATEGORY:

                dialog = new Dialog(CatalogMenuActivity.this);
                dialog.setContentView(R.layout.catalog_new_category_dialog);

                dialog.setTitle("New Category");
                ((dialog.findViewById(R.id.catalog_dialog_category_save_button))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CatalogMenuActivity.this.addCategory();
                    }
                });
                ((dialog.findViewById(R.id.button_save_cancel))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        removeDialog(CREATE_CATEGORY);
                    }
                });


                break;
            case CREATE_PRODUCT:
                dialog = new Dialog(CatalogMenuActivity.this);
                dialog.setContentView(R.layout.catalog_new_product_dialog);

                dialog.setTitle("New Product");
                ((dialog.findViewById(R.id.catalog_dialog_category_save_button))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CatalogMenuActivity.this.addProduct();
                    }
                });
                ((dialog.findViewById(R.id.button_save_cancel))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        removeDialog(CREATE_PRODUCT);
                    }
                });

                break;
            case CREATE_MENU:
                dialog = new Dialog(CatalogMenuActivity.this);
                dialog.setContentView(R.layout.catalog_new_menu_dialog);

                dialog.setTitle("New Product");
                ((dialog.findViewById(R.id.catalog_dialog_category_save_button))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CatalogMenuActivity.this.addMenu();
                    }
                });
                ((dialog.findViewById(R.id.button_save_cancel))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        removeDialog(CREATE_MENU);
                    }
                });

                break;
            case CREATE_EDIT_PROPERTY:
                dialog = new Dialog(CatalogMenuActivity.this);
                dialog.setContentView(R.layout.catalog_change_property_dialog);

                dialog.setTitle("Edit property");
                ((dialog.findViewById(R.id.catalog_dialog_category_save_button))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        CatalogMenuActivity.this.addProperty();
                    }
                });
                ((dialog.findViewById(R.id.button_save_cancel))).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        removeDialog(CREATE_EDIT_PROPERTY);
                    }
                });

                break;

            default:
                dialog = null;
        }
        return dialog;
    }


    public void onListViewProductClick(ProductType productType) {
        CatalogDisplayFragment viewer = (CatalogDisplayFragment) getFragmentManager().findFragmentById(R.id.detail_fragment);

        if (viewer == null || !viewer.isInLayout()) {
            Intent detailIntent = new Intent(getApplicationContext(), CatalogDisplayActivity.class);
            startActivity(detailIntent);
        } else {
            viewer.displayProductDetail(productType);
        }
    }

    public void onListViewMenuClick(MenuType menu) {
        CatalogDisplayFragment viewer = (CatalogDisplayFragment) getFragmentManager().findFragmentById(R.id.detail_fragment);

        if (viewer == null || !viewer.isInLayout()) {
            Intent detailIntent = new Intent(getApplicationContext(), CatalogDisplayActivity.class);
            startActivity(detailIntent);
        } else {
            viewer.displayMenu(menu);
        }
    }

    public void onListViewCategoryClick(CatalogCategory category) {
        CatalogDisplayFragment viewer = (CatalogDisplayFragment) getFragmentManager().findFragmentById(R.id.detail_fragment);

        if (viewer == null || !viewer.isInLayout()) {
            Intent detailIntent = new Intent(getApplicationContext(), CatalogDisplayActivity.class);
            startActivity(detailIntent);
        } else {
            viewer.displayCategory(category);
        }
    }

    public void openDialogNewCategory() {
        showDialog(CREATE_CATEGORY);
    }

    public void openDialogNewProduct() {
        showDialog(CREATE_PRODUCT);
    }

    public void openDialogNewMenu() {
        showDialog(CREATE_MENU);
    }

    public void openDialogPropertyEdit(Long idProductType, CatalogPropertyEnum tag) {
        idSelectedProduct = idProductType;
        selectedProperty = tag;
        showDialog(CREATE_EDIT_PROPERTY);

    }

    public void addCategory() {
        EditText editText = (EditText) dialog.findViewById(R.id.catalog_dialog_category_edittext_name);
        CatalogCategory newCategory = new CatalogCategory(editText.getText().toString(), "pouet");
        newCategory.saveToDatabase(getBaseContext());

        CatalogCategory actualCategory = CatalogCategory.getOne(getBaseContext(), idActualCategory);

        actualCategory.addChildCategory(newCategory);
        actualCategory.saveToDatabase(getBaseContext());
        SyncTaskManager.insertCategoryToServer(getBaseContext(), newCategory, actualCategory);

        this.dialog.dismiss();
        removeDialog(CREATE_CATEGORY);

        CatalogMenuFragment actualFragment = (CatalogMenuFragment) getFragmentManager().findFragmentById(R.id.menu_fragment);
        actualFragment.getCategory(idActualCategory, false);

    }


    public void addProduct() {
        EditText editText = (EditText) dialog.findViewById(R.id.catalog_dialog_product_edittext_name);
        final ProductType productType = new ProductType(editText.getText().toString(), 2, "Tap to change!");
        RecommendedPrice recommendedPrice = new RecommendedPrice(0f, null);
        recommendedPrice.saveToDatabase(getBaseContext());
        productType.getRecommendedPriceHashMap().put(null, recommendedPrice);
        productType.saveToDatabase(getBaseContext());

        final CatalogCategory actualCategory = CatalogCategory.getOne(getBaseContext(), idActualCategory);

        actualCategory.addChildProductType(productType);
        actualCategory.saveToDatabase(getBaseContext());
        SyncTaskManager.insertProductTypeToServer(getBaseContext(), productType, actualCategory);

        this.dialog.dismiss();
        removeDialog(CREATE_PRODUCT);

        CatalogMenuFragment actualFragment = (CatalogMenuFragment) getFragmentManager().findFragmentById(R.id.menu_fragment);
        actualFragment.getCategory(idActualCategory, false);

    }

    public void addMenu() {
        EditText editText = (EditText) dialog.findViewById(R.id.catalog_dialog_menu_edittext_name);
        final MenuType menuType = new MenuType(editText.getText().toString());
        menuType.saveToDatabase(getBaseContext());

        final CatalogCategory actualCategory = CatalogCategory.getOne(getBaseContext(), idActualCategory);

        actualCategory.addChildMenuType(menuType);
        actualCategory.saveToDatabase(getBaseContext());
        SyncTaskManager.InsertMenuTypeToServer(menuType, actualCategory);

        this.dialog.dismiss();
        removeDialog(CREATE_MENU);

        CatalogMenuFragment actualFragment = (CatalogMenuFragment) getFragmentManager().findFragmentById(R.id.menu_fragment);
        actualFragment.getCategory(idActualCategory, false);

    }


    public void addProperty() {
        EditText editText = (EditText) dialog.findViewById(R.id.catalog_dialog_property_edittext_name);
        final ProductType selectedProduct = ProductType.getOne(getBaseContext(), idSelectedProduct);
        try {
            if (selectedProperty == CatalogPropertyEnum.DESCRIPTION) {
                selectedProduct.setDescription(editText.getText().toString());
            }
            if (selectedProperty == CatalogPropertyEnum.LOCAL_PRICE) {
                if (Store.getLocalStore(getBaseContext()) != null) {
                    selectedProduct.setLocalPrice(Store.getLocalStore(getBaseContext()), null, Float.parseFloat(editText.getText().toString()));
                    Toast toast = Toast.makeText(getBaseContext(), "Price saved", Toast.LENGTH_SHORT);
                    toast.show();
                } else {
                    Toast toast = Toast.makeText(getBaseContext(), "Select a local store...", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
            if (selectedProperty == CatalogPropertyEnum.RECOMMENDED_PRICE) {
                if (selectedProduct.getRecommendedPriceHashMap().size() == 0) {
                    selectedProduct.getRecommendedPriceHashMap().put(null, new RecommendedPrice(new Float(editText.getText().toString()), null));
                } else {
                    HashMap<Long, RecommendedPrice> pouet = selectedProduct.getRecommendedPriceHashMap();
                    Iterator<Long> iterator = pouet.keySet().iterator();
                    while (iterator.hasNext()) {
                        Long id = iterator.next();
                        DeliveryType d = null;
                        if (id != null) {
                            d = DeliveryType.getOne(getBaseContext(), id);
                        }
                        pouet.get(d).setValue(new Float(editText.getText().toString()));
                        pouet.get(d).saveToDatabase(this.getBaseContext());

                    }
                }
            }
            selectedProduct.saveToDatabase(getBaseContext());
            SyncTaskManager.updateProductTypeToServer(selectedProduct);

        } catch (NumberFormatException e) {
            e.printStackTrace();
            Toast toast = Toast.makeText(getBaseContext(), "NumberOnly !", Toast.LENGTH_SHORT);
            toast.show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "Fail ... :/", Toast.LENGTH_SHORT).show();
        }
        dialog.dismiss();
        removeDialog(CREATE_EDIT_PROPERTY);
        CatalogMenuFragment actualMenuFragment = (CatalogMenuFragment) getFragmentManager().findFragmentById(R.id.menu_fragment);
        actualMenuFragment.getCategory(idActualCategory, false);

        CatalogDisplayFragment actualDisplayFragment = (CatalogDisplayFragment) getFragmentManager().findFragmentById(R.id.detail_fragment);
        actualDisplayFragment.displayProductDetail(selectedProduct);

    }


    public void deleteObject(final Object object) {
        if (object instanceof CatalogCategory) {
            ((CatalogCategory) object).removeFromDatabase(getBaseContext());

            SyncTaskManager.deleteProductCategoryToServer((CatalogCategory) object);

        } else if (object instanceof ProductType) {
            CatalogCategory catalogCategory = CatalogCategory.getOne(getBaseContext(), idActualCategory);
            catalogCategory.getChildProductTypeId().remove(((ProductType) object).getIdDB());
            catalogCategory.saveToDatabase(getBaseContext());
            ((ProductType) object).removeFromDatabase(getBaseContext());
            SyncTaskManager.deleteProductTypeToServer((ProductType) object);

        } else if (object instanceof MenuType) {
            ((MenuType) object).removeFromDatabase(getBaseContext());
            SyncTaskManager.deleteMenuTypeToServer((MenuType) object);

        } else {
            Toast toast = Toast.makeText(getBaseContext(), "An error as occured!", Toast.LENGTH_SHORT);
            toast.show();
        }
        Toast toast = Toast.makeText(getBaseContext(), "Deleted!", Toast.LENGTH_SHORT);
        toast.show();
        CatalogMenuFragment actualMenuFragment = (CatalogMenuFragment) getFragmentManager().findFragmentById(R.id.menu_fragment);
        actualMenuFragment.getCategory(idActualCategory, false);

    }


}
